package com.example.zbh.dsliao.ui.activty;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.b.g;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMGroup;
import com.easemob.chat.EMGroupManager;
import com.easemob.chat.GroupChangeListener;
import com.easemob.exceptions.EaseMobException;
import com.example.zbh.dsliao.R;
import com.example.zbh.dsliao.constant.Constant;
import com.example.zbh.dsliao.db.DatabaseHelper;
import com.example.zbh.dsliao.db.entity.UserContact;
import com.example.zbh.dsliao.thread.GlobalThread;
import com.example.zbh.dsliao.thread.ThreadPool;
import com.example.zbh.dsliao.ui.adapter.GroupDetailsAdapter;
import com.example.zbh.dsliao.ui.adapter.RemoveMemberAdapter;
import com.example.zbh.dsliao.utils.FullyGridLayoutManager;
import com.example.zbh.dsliao.utils.PreferenceHelper;
import com.example.zbh.dsliao.view.CustomChangeDialog;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Created by zbh on 15/11/30.
 */
public class GroupDetailsActivity extends BaseActivity implements View.OnClickListener, GroupDetailsAdapter.OnGroupMemberItemClickListener, RemoveMemberAdapter.OnRemoveMemberItemClickListener, GlobalThread.GetGroupListener {

    private RecyclerView recyclerView;
    private FullyGridLayoutManager fullyGridLayoutManager;
    private GroupDetailsAdapter detailsAdapter;
    private TextView tv_group_id, sure_tv, black_list;
    private Button btn_exit_grp, exit_group;
    private String id;
    private RelativeLayout clear_all_history, rl_change_group_name;
    private CustomChangeDialog dialog;
    private LinearLayout change_group_name, back;
    private EditText ed_name;
    private ImageView swith_image;
    private boolean isHidden = false;
    private EMGroup group;
    private List<String> members = new ArrayList<>();
    private RemoveMemberAdapter removeMemberAdapter;
    private Handler handler;
    private ThreadPool pool;
    private GlobalThread groupThread;

    @Override
    protected int getLayOut() {
        return R.layout.activity_group_details;
    }

    @Override
    protected void initView() {
        recyclerView = findeView(R.id.recyclerView);
        tv_group_id = findeView(R.id.tv_group_id);
        btn_exit_grp = findeView(R.id.btn_exit_grp);
        clear_all_history = findeView(R.id.clear_all_history);
        rl_change_group_name = findeView(R.id.rl_change_group_name);
        change_group_name = findeView(R.id.change_group_name);
        ed_name = findeView(R.id.ed_name);
        sure_tv = findeView(R.id.sure_tv);
        back = findeView(R.id.back);
        swith_image = findeView(R.id.swith_image);
        black_list = findeView(R.id.black_list);
        exit_group = findeView(R.id.exit_group);
    }

    @Override
    protected void initData() {
        id = getIntent().getStringExtra(Constant.GROUPUSERID);
        pool = ThreadPool.getInstance();
        groupThread = new GlobalThread(Constant.GROUPDETAILSGETGROUP, id);
        groupThread.setgetGroupListener(this);
        pool.addThread(Constant.GROUPDETAILSGETGROUP, groupThread);
        pool.executeThread(Constant.GROUPDETAILSGETGROUP);
        tv_group_id.setText("群ID    " + id);
        isHidden = PreferenceHelper.getInstance().getCurrentGroupStatus(id + Constant.ISHIDDENFROUPMESSAGE);
        if (isHidden) {
            swith_image.setImageResource(R.mipmap.dl_open_icon);
        } else {
            swith_image.setImageResource(R.mipmap.dl_close_icon);
        }
        btn_exit_grp.setOnClickListener(this);
        exit_group.setOnClickListener(this);
        clear_all_history.setOnClickListener(this);
        rl_change_group_name.setOnClickListener(this);
        sure_tv.setOnClickListener(this);
        back.setOnClickListener(this);
        swith_image.setOnClickListener(this);
        fullyGridLayoutManager = new FullyGridLayoutManager(this, 4);
        recyclerView.setLayoutManager(fullyGridLayoutManager);
        detailsAdapter = new GroupDetailsAdapter(this);
        removeMemberAdapter = new RemoveMemberAdapter(this);
        removeMemberAdapter.setOnRemoveMemberItemClickListener(this);
        detailsAdapter.setOnGroupMemberItemClickListener(this);
        black_list.setOnClickListener(this);
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                switch (msg.what) {
                    case 100:
                        showGroupMembers();
                        break;
                    case 200:
                        showGroupMembers();
                        break;
                }
                return false;
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_exit_grp:
                showExitDialog();
                break;
            case R.id.clear_all_history:
                showClearDialog();
                break;
            case R.id.rl_change_group_name:
                change_group_name.setVisibility(View.VISIBLE);
                break;
            case R.id.sure_tv:
                change_group_name.setVisibility(View.GONE);
                changeGroupName();
                break;
            case R.id.back:
                finish();
                break;
            case R.id.swith_image:
                isHidden = !isHidden;
                if (isHidden) {//屏蔽
                    swith_image.setImageResource(R.mipmap.dl_open_icon);
                    hiddenGroupMessage();
                } else {//解开屏蔽
                    swith_image.setImageResource(R.mipmap.dl_close_icon);
                    releaseGroupMessage();
                }
                PreferenceHelper.getInstance().setCurrentGroupStatus(id + Constant.ISHIDDENFROUPMESSAGE, isHidden);
                break;
            case R.id.black_list:
                Intent intent = new Intent();
                intent.setClass(this, GroupBlackListActivity.class);
                intent.putExtra("userId", id);
                startActivity(intent);
                break;
            case R.id.exit_group:
                membersExitGroup();//不是群主
                break;
        }
    }

    //群组适配器显示群成员
    public void showGroupMembers() {
        if (group.getOwner().equals(EMChatManager.getInstance().getCurrentUser())) {
            exit_group.setVisibility(View.GONE);
        } else {
            btn_exit_grp.setVisibility(View.GONE);
            rl_change_group_name.setVisibility(View.GONE);
        }
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < members.size(); i++) {
            UserContact userContact = DatabaseHelper.getInstance().queryContactPeopleByName(members.get(i));
            if (userContact != null) {
                String nickName = userContact.getNickname();
                if (nickName != null) {
                    list.add(nickName);
                } else {
                    list.add(members.get(i));
                }
            } else {
                list.add(members.get(i));
            }
        }
        Log.i("mingzi", list.toString());
        recyclerView.setAdapter(detailsAdapter);
        detailsAdapter.addData(list, group);
    }

    //退出群聊
    private void membersExitGroup() {
        dialog = new CustomChangeDialog(this, "是否退出该群?", View.GONE, "", "确定", "取消");
        dialog.show();
        dialog.setCustomChangeDialogListener(new CustomChangeDialog.CustomChangeDialogListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.changeTwoBtn:
                        initMembersExitGroupThread();
                        break;
                    case R.id.cancleBtn:
                        dialog.dismiss();
                        break;
                }
            }
        });


    }
    //初始化群成员退出群聊线程
    private void initMembersExitGroupThread() {
        GlobalThread membersExitGroupThread = new GlobalThread(Constant.GROUPDETAILSMEMBERSEXITGROUP, id);
        membersExitGroupThread.setgetGroupListener(this);
        pool.addThread(Constant.GROUPDETAILSMEMBERSEXITGROUP, membersExitGroupThread);
        pool.executeThread(Constant.GROUPDETAILSMEMBERSEXITGROUP);
    }
    //清除聊天记录
    private void showClearDialog() {
        dialog = new CustomChangeDialog(this, "是否清除聊天记录?", View.GONE, "", "确定", "取消");
        dialog.show();
        dialog.setCustomChangeDialogListener(new CustomChangeDialog.CustomChangeDialogListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.changeTwoBtn:
                        clearGroupHistory();
                        dialog.dismiss();
                        break;
                    case R.id.cancleBtn:
                        dialog.dismiss();
                        break;
                }
            }
        });

    }

    //修改群组名称
    private void changeGroupName() {
        String content = ed_name.getText().toString();
        if (content.length() > 0 && content != null) {
            GlobalThread changeGroupName = new GlobalThread(content, id, Constant.GROUPDETAILSCHANGE);
            pool.addThread(Constant.GROUPDETAILSCHANGE, changeGroupName);
            pool.executeThread(Constant.GROUPDETAILSCHANGE);
        } else {
            Toast.makeText(this, "群名不能为空", Toast.LENGTH_SHORT).show();
        }
    }

    //解散群组
    private void showExitDialog() {
        dialog = new CustomChangeDialog(this, "是否解散该群组?", View.GONE, "", "确定", "取消");
        dialog.show();
        dialog.setCustomChangeDialogListener(new CustomChangeDialog.CustomChangeDialogListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.changeTwoBtn:
                        exitGroup();
                        dialog.dismiss();
                        Intent intent = new Intent();
                        intent.putExtra("result", "确定");
                        setResult(RESULT_OK, intent);
                        GroupDetailsActivity.this.finish();
                        break;
                    case R.id.cancleBtn:
                        dialog.dismiss();
                        break;
                }
            }
        });

    }

    //清除聊天记录
    private void clearGroupHistory() {
        EMChatManager.getInstance().clearConversation(id);
        Intent intent = new Intent();
        intent.putExtra("clear", "清空聊天记录");
        setResult(RESULT_OK, intent);
    }

    //屏蔽群聊消息
    public void hiddenGroupMessage() {
        GlobalThread messageThread = new GlobalThread(Constant.GROUPDETAILSGROUPMESSAGE, id);
        pool.addThread(Constant.GROUPDETAILSGROUPMESSAGE, messageThread);
        pool.executeThread(Constant.GROUPDETAILSGROUPMESSAGE);
    }

    //解除屏蔽群
    public void releaseGroupMessage() {
        GlobalThread releaseGroudHideThread = new GlobalThread(Constant.GROUPDETAILSRELEASEGROUPMESSAGE, id);
        pool.addThread(Constant.GROUPDETAILSRELEASEGROUPMESSAGE, releaseGroudHideThread);
        pool.executeThread(Constant.GROUPDETAILSRELEASEGROUPMESSAGE);

    }

    //退出群组
    private void exitGroup() {
        GlobalThread exitGroupThread = new GlobalThread(Constant.GROUPDETAILSEXIT, id);
        pool.addThread(Constant.GROUPDETAILSEXIT, exitGroupThread);
        pool.executeThread(Constant.GROUPDETAILSEXIT);
    }

    //移动联系人到黑名单
    @Override
    public void removeToblack(List<String> list, int postion) {
        if (postion != 0 && postion != list.size() && postion != list.size() + 1) {
            final String blackName = list.get(postion);
            dialog = new CustomChangeDialog(this, "是否将" + blackName + "移入进此群的黑名单?", View.GONE, "", "确定", "取消");
            dialog.show();
            dialog.setCustomChangeDialogListener(new CustomChangeDialog.CustomChangeDialogListener() {
                @Override
                public void onClick(View view) {
                    switch (view.getId()) {
                        case R.id.changeTwoBtn:
                            UserContact contact = DatabaseHelper.getInstance().queryContactPeopleBynickName(blackName);
                            if (contact != null) {
                                initRemoveThread(contact.getUsername());
                            } else {
                                initRemoveThread(blackName);
                            }
                            break;
                        case R.id.cancleBtn:
                            dialog.dismiss();
                            break;
                    }
                }
            });
        }
    }

    //初始化移动群成员到黑名单的线程
    private void initRemoveThread(String name) {
        GlobalThread removeThread = new GlobalThread(name, id, Constant.GROUPDETAILSREMOVE);
        removeThread.setgetGroupListener(this);
        pool.addThread(Constant.GROUPDETAILSREMOVE, removeThread);
        pool.executeThread(Constant.GROUPDETAILSREMOVE);
    }

    //点击加号增加群成员
    @Override
    public void addMember(List<String> list, int position) {
        if (position == list.size()) {
            Intent intent = new Intent();
            intent.setClass(this, AddGroupMemberActivity.class);
            intent.putExtra("userId", id);
            startActivityForResult(intent, 200);
        }

    }

    //点击减号显示群成员
    @Override
    public void removeMember(List<String> list, int position) {
        if (position == list.size() + 1) {
            removeMemberAdapter.addData(list);
            recyclerView.setAdapter(removeMemberAdapter);
        }


    }


    //点击头像进行删除
    @Override
    public void onRemoveMemberItemClick(List<String> list, int position) {
        final String name = list.get(position);
        UserContact user = DatabaseHelper.getInstance().queryContactPeopleBynickName(name);
        if (user != null) {
            initHeaderRemoveThread(user.getUsername());
        } else {
            initHeaderRemoveThread(name);
        }

    }

    //初始化点击头像进行删除的线程
    public void initHeaderRemoveThread(String name) {
        GlobalThread headerRemoveThread = new GlobalThread(name, id, Constant.GROUPDETAILSHEADERREMOVE);
        headerRemoveThread.setgetGroupListener(this);
        pool.addThread(Constant.GROUPDETAILSHEADERREMOVE, headerRemoveThread);
        pool.executeThread(Constant.GROUPDETAILSHEADERREMOVE);

    }

    //添加联系人的结果回调
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 200) {
                if (data.getStringExtra("tianjia").equals("添加")) {
                    pool.addThread(Constant.GROUPDETAILSGETGROUP, groupThread);
                    pool.executeThread(Constant.GROUPDETAILSGETGROUP);
                    Log.i("nannannan", "getGroup");
                }
            }
        }

    }

    //开启线程后的结果回调
    @Override
    public void showGroupResult(String type, EMGroup emGroup) {
        if (type.equals(Constant.GROUPDETAILSGETGROUP)) {
            group = emGroup;
            members = group.getMembers();
            if (group == null) {
                finish();
                return;
            }
            Log.i("nannannan", "getGroup");
            handler.sendEmptyMessage(200);
        }
        if (type.equals(Constant.GROUPDETAILSREMOVE)) {
            group = emGroup;
            members = group.getMembers();
            dialog.dismiss();
            handler.sendEmptyMessage(100);
        }
        if (type.equals(Constant.GROUPDETAILSHEADERREMOVE)) {
            group = emGroup;
            members = group.getMembers();
            handler.sendEmptyMessage(100);
        }
        if (type.equals(Constant.GROUPDETAILSMEMBERSEXITGROUP)) {
            Intent intent = new Intent();
            intent.putExtra("exit", "退出群聊");
            setResult(RESULT_OK, intent);
            finish();
        }
    }
}
